package cloud.tianai.mate.captcha.interceptor.impl;

import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.interceptor.Context;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
import cloud.tianai.mate.captcha.interceptor.group.FeaturesCaptchaInterceptorGroup;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


/**
 * @Author: 天爱有情
 * @date 2023/9/14 14:16
 * @Description 请求数量校验
 */
@Slf4j
public class CaptchaRequestNumInterceptor implements CaptchaInterceptor {
    @Getter
    @Setter
    private Integer checkNum = 20;
    public static final String requestCountKey = "requestCount";

    @Override
    public String getName() {
        return "request_num_check";
    }

    @Override
    public ApiResponse<?> beforeValid(Context context, String type, ImageCaptchaTrack imageCaptchaTrack, AnyMap validData) {
        AnyMap featureMap = context.getData(FeaturesCaptchaInterceptorGroup.DATA_FEATURES, AnyMap.class);
        if (featureMap != null) {
            // 记录当前IP验证验证次数
            Integer count = featureMap.getInt(requestCountKey, 0);
            count++;
            featureMap.put(requestCountKey, count);
            if (count >= checkNum) {
                // 打入黑名单
                featureMap.put(DisableCaptchaInterceptor.DISABLE_KEY, true);
            }
        }
        return ApiResponse.SUCCESS;
    }
}
